package com.blb.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 自定义Callable类
 */
class MyCallable implements Callable<Long>{

    //完成运算，返回结果
    @Override
    public Long call() throws Exception {
        Long sum = 0L;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        System.out.println(Thread.currentThread().getName() + "完成计算");
        return sum;
    }
}


public class Demo3Callable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建FutureTask对象，传入Callable实现对象
        FutureTask<Long> futureTask = new FutureTask<>(new MyCallable());
        //创建Thread对象，传入FutureTask对象
        Thread thread = new Thread(futureTask);
        //执行线程
        thread.start();
        //获得结果
        System.out.println("计算结果：" + futureTask.get());
    }
}
